import selectors
import socket
response_body = """\
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试网页</title>
</head>
<body>
    <h1 style="color:red">欢迎访问Magedu-{}</h1>
</body>
</html>
"""
response_header = """\
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: {}
X-Server: Vic.magedu.com
Connection: keep-alive

"""




def get_response() -> bytes:
    html = response_body.format("IO多路复用，事件驱动").encode("utf-8")
    response = response_header.format(len(html)).replace("\n", "\r\n").encode() + html

    return response

def fn1(server):
    conn, raddr = server.accept()
    conn.setblocking(False)

    print(conn, raddr, '~~~~~~~~~~')
    k = st.register(conn, selectors.EVENT_READ, fn2)
    print(k)
def fn2(conn):
    try:
        data = conn.recv(1024)
        print(data, "@@@@")
        if not data:
            print('bye~', conn.getpeername())
            return
        #conn.send(b"Hello World")
        conn.send(get_response())

        print("+" * 30)
    except Exception as e:
        print(e, "~~~~~~~~~~~~~~~~~~")
    finally:
        conn.close()




if __name__ == "__main__":
    st = selectors.DefaultSelector()
    server = socket.socket()
    server.setblocking(False)
    server.bind(('0.0.0.0', 9999))
    server.listen()
    print(server)

    k = st.register(server, selectors.EVENT_READ, fn1)
    print(type(k),k)
    while True:
        for key, mask in st.select():
            print(key.fileobj, key.fd, key.events, key.data)
            key.data(key.fileobj)
            # key
            # if key.fileobj == server:
            #     key.fileobj.accept()
            # elif key.fileobj == fileobj2:
            #     key.fileobj.recv()
            # elif key.fileobj == fileobj3:
            #     pass
            # else:
            #     pass


    #conn, raddr = server.accept()
    #print(type(conn),conn)
    #conn.close()
    #server.close()
    print('~' * 30)